<template>
  <div>
    <!-- 弹出添加信息对话框 -->
    <el-dialog v-model="dialogFormVisible" title="添加信息">
      <el-form :model="formData" ref="form" :rules="rules">
        <el-form-item label="学号" prop="sid" :label-width="formLabelWidth">
          <el-input v-model="formData.sid" autocomplete="off" />
        </el-form-item>
        <el-form-item label="姓名" prop="name" :label-width="formLabelWidth">
          <el-input v-model="formData.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="性别" prop="sex" :label-width="formLabelWidth">
          <!-- <el-input v-model="formData.sex" autocomplete="off" /> -->
          <el-radio-group v-model="formData.sex" class="ml-4">
            <el-radio label="男" size="large">男</el-radio>
            <el-radio label="女" size="large">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age" :label-width="formLabelWidth">
          <el-input v-model.number="formData.age" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="专业方向"
          prop="sclass"
          :label-width="formLabelWidth"
        >
          <!-- <el-input v-model="formData.sclass" autocomplete="off" /> -->
          <el-select v-model="formData.sclass" placeholder="请选择班级">
            <el-option
              v-model="formData.sclass"
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="家庭住址"
          prop="address"
          :label-width="formLabelWidth"
          v-model="formData.address"
        >
          <el-cascader
            size="large"
            :options="optionsArea"
            v-model="selectedOptions"
            @change="handleChange"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item
          label="联系方式"
          prop="phone"
          :label-width="formLabelWidth"
        >
          <el-input v-model="formData.phone" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="sure(form)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查询 重置按钮 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input
          v-model="formInline.name"
          placeholder="请输入姓名查询"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="find">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @click="submit">导出选中的数据</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @click="toUpload">批量添加学生信息</el-button>
      </el-form-item>
      <el-form-item>
        <!-- 新增按钮 -->
        <el-button class="addButton" type="success" @click="add"
          >添加学生</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 学生信息数据列表 -->
    <el-table
      :data="
        Data.tableData.slice(
          (currentPage - 1) * pageSize,
          currentPage * pageSize
        )
      "
      :default-sort="{ prop: 'sid', order: 'descending' }"
      border
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" align="center"> </el-table-column>
      <el-table-column prop="sid" label="学号" align="center" min-width="10%">
      </el-table-column>
      <el-table-column prop="name" label="姓名" align="center" min-width="10%">
      </el-table-column>
      <el-table-column prop="sex" label="性别" align="center" min-width="10%">
      </el-table-column>
      <el-table-column prop="age" label="年龄" align="center" min-width="10%">
      </el-table-column>

      <el-table-column
        prop="sclass"
        label="专业方向"
        align="center"
        min-width="10%"
      >
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址"
        align="center"
        min-width="10%"
      >
      </el-table-column>
      <el-table-column
        prop="phone"
        label="联系方式"
        align="center"
        min-width="10%"
      >
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="10%">
        <template #default="scope">
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon-color="#626AEF"
            title="确定删除该学生信息吗?"
            @confirm="del(scope.row)"
          >
            <template #reference>
              <el-button type="danger" round>
                <Delete style="width: 1.2em; height: 1.2em; margin-right: 0" />
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 分页 -->
  <div class="pagination">
    <el-pagination
      background
      :page-size="pageSize"
      layout="prev, pager, next"
      :total="Data.tableData.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
    />
  </div>
</template>

<script setup>
import router from '@/router/index'
import { ElMessage } from "element-plus";
import {
  students,
  DelStudent,
  addStudents,
  findStudent,
  findCourse,
} from "@/api/api";
import { reactive, ref, onMounted } from "vue";
import mitt from "../../mitt/index.js";
// regionDataPlus是省市区三级联动数据（带“全部”选项）
// CodeToText是个大对象，属性是区域码，属性值是汉字 用法例如：CodeToText['110000']输出北京市
import { regionDataPlus, CodeToText } from "element-china-area-data";
import xlsx from "xlsx";
let selectionData = reactive({
  data: [],
});
const selectionChange = (val) => {
  selectionData.data = val;
};

const submit = () => {
  if (selectionData.data.length <= 0) {
    ElMessage({
      type: "success",
      message: "请选择要导出的数据！",
    });
    return;
  }
  // 指定要导出的格式
  let arr = selectionData.data.map((item) => {
    return {
      学号: item.sid,
      姓名: item.name,
      性别: item.sex,
      年龄: item.age,
      班级: item.sclass,
      住址: item.address,
      联系方式: item.phone,
    };
  });
  let sheet = xlsx.utils.json_to_sheet(arr); //将数据格式转换为sheet格式
  let book = xlsx.utils.book_new(); //新建表格
  xlsx.utils.book_append_sheet(book, sheet, "sheet1"); //向book这个表格插入sheet1这一页签，数据是sheet
  xlsx.writeFile(book, `user${new Date().getTime()}.xls`);
};
const toUpload=()=>{
   router.push("/home/upload");
}
const optionsArea = regionDataPlus;
const selectedOptions = ref([]);
// let {proxy}=getCurrentInstance()
// 获取总数据
let Data = reactive({
  tableData: [],
});
// let dialogTableVisible = ref(false);
let dialogFormVisible = ref(false); //控制添加对话框显示与隐藏
// let dialogCourse=ref(false) //控制选课弹框的显示与隐藏
const formLabelWidth = "140px";
// 添加对话框中的内容
let formData = reactive({
  sid: "",
  name: "",
  sex: "男",
  age: "",
  sclass: "",
  address: [],
  phone: "",
});

// 课程信息数据
let courseData = reactive({
  course: [],
});
// 分页数据
let currentPage = ref(1); //当前页数
let pageSize = ref(10); //每页显示条数

let total = ref(0); //总条数

// const value = ref("");
let studentSid = ref(2);
// 班级选择
const options = [
  {
    value: "前端",
    label: "前端",
  },
  {
    value: "后端",
    label: "后端",
  },
  {
    value: "网安",
    label: "网安",
  },
  {
    value: "数媒",
    label: "数媒",
  },
  //  {
  //     value: "大数据2班",
  //     label: "大数据2班",
  //   }
];
// 选择地区
const handleChange = () => {
  console.log(selectedOptions.value);
  if (selectedOptions.value[0] != null && selectedOptions.value[1] != null) {
    const str =
      CodeToText[selectedOptions.value[0]] +
      CodeToText[selectedOptions.value[1]] +
      CodeToText[selectedOptions.value[2]];
    console.log(str);
    formData.address = str;
  }
};
// 查询用的name属性
let formInline = reactive({
  name: "",
});

onMounted(() => {
  getData();
  // getCourseData()
});
// 调用接口 获取数据
let getData = async (params) => {
  await students(params).then((res) => {
    console.log(res);
    if (res.data.code === 0) {
      Data.tableData = res.data.data.list;
      total.value = res.data.total;
      // console.log('111')
      // console.log(res.data.data.list)
      // console.log(res.data.data.total[0].total)
    }
  });
};

// 删除按钮
let del = (row) => {
  console.log(row);
  DelStudent(row.sid).then((res) => {
    console.log("111", res);
    if (res.data.status === 200) {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      // 删除成功后重新渲染数据
      getData();
    }
  });
};

let add = () => {
  // console.log("111");

  // 用于将表单置空
  // formData = {
  //   name: "",
  //   sex: "",
  //   age: "",
  //   address: [],
  //   time: "",
  //   phone: "",
  // };
  dialogFormVisible.value = true;
};
// 弹出对话框表单验证
let rules = {
  sid: [{ required: true, message: "请输入学号" }],
  name: [{ required: true, message: "请输入姓名" }],
  sex: [{ required: true }],
  age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
  sclass: [{ required: true, message: "请输入班级" }],
  address: [{ required: true, message: "请输入地址" }],
  phone: [{ required: true, message: "请输入联系方式" }],
};
const form = ref(null);
// 对话框中确定按钮
let sure = async (form) => {
  // if (!form) return;
  // if(formData.sid==Data.tableData.sid){
  //   alert(111)
  // }
  await form.validate((valid) => {
    if (valid) {
      console.log("新增数据", formData);

      // 通过state为true或者false来判断
      // 当为true时：代表为添加信息
      // 为false时：代表修改信息
      // if (this.state) {
      addStudents(formData).then((res) => {
        console.log("对话框学号", formData.sid);
        // 将列表数组中的sid取出，单独组成数组
        var sid_list = Data.tableData.map(function (item) {
          return item.sid;
        }); //item为数组中的一项，在这里相当于其中一个对象
        console.log("列表学号", sid_list);
        // 判断 弹框中的sid是否存在如果不在 就return
        if (sid_list.indexOf(formData.sid) !== -1) {
          ElMessage({
            type: "warning",
            message: "该学生已存在",
          });
          return;
        }

        if (res.data.status === 200) {
          getData();
          ElMessage({
            type: "success",
            message: res.data.message,
          });
          //          formData = {
          //   name: "",
          //   sex: "",
          //   age: "",
          //   address: [],
          //   time: "",
          //   phone: "",
          // };
          dialogFormVisible.value = false; //关闭弹框
        }
      });

      // } else {
      //   updateInfo(this.form).then((res) => {
      //     if (res.data.status === 200) {
      //       this.getData();
      //       this.$refs["form"].resetFields();
      //       this.dialogFormVisible = false; //关闭弹框
      //       this.$message({
      //         type: "success",
      //         message: res.data.message,
      //       });
      //     }
      //   });
      // }
    }
  });
};

// 查询按钮
const find = async () => {
  await findStudent(formInline).then((res) => {
    console.log(res);
    if (res.data.status === 200) {
      Data.tableData = res.data.data.list;
      total.value = res.data.total;
    }
  });
};
// 重置操作
const reset = () => {
  formInline = {}; //先将formInline中的数据清空
  getData(); //重新渲染数据
};
// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  console.log(`每页 ${val} 条`);
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
};
// 查看某位学生选课信息及成绩
let findCourseGrade = (row) => {
  console.log(row.sid); //查看此学生sid
  findCourse(row.sid).then((res) => {
    console.log("选课信息", res.data);
    courseData.course = res.data.data.list;
  });
};
// 选课弹框采用兄弟组件间传值
let gotoSelection = () => {
  // dialogCourse.value=true
  // console.log(row.sid)
  // proxy.$mitt.emit('mittFn',row.sid)
  console.log(studentSid.value);
  mitt.emit("mittevent", studentSid.value);
};
</script>

<style>
/* .addButton {
  display: block;
  position: absolute;
  top: 20px;
  right: 26px;
  height: 50px;
  width: 150px;
  font-size: 26px;
} */
.demo-form-inline {
  padding-top: 35px;
}
.pagination {
  display: block;
  margin: 10px auto;
}
</style>